package com.haredot.controller;


import com.haredot.entity.Order;
import com.haredot.entity.User;
import com.haredot.handler.TokenContextHolder;
import com.haredot.result.R;
import com.haredot.service.OrderService;
import com.haredot.utils.MD5Utils;
import com.haredot.validation.Insert;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.hibernate.validator.constraints.Range;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Resource
    private OrderService orderService ;


    /**
     * 获取二维码生成网络地址需要的参数
     */
    @PostMapping("/qrcode/{cid}")
    public R<?> qrcode(@PathVariable("cid") Long cid) {

        long epochSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        // 简单的 防止 浏览器 篡改数据
        String message = "cid=" + cid + "&key=haredot&time=" + epochSecond;
        Map<String, Object> data = Map.of("cid", cid, "time", epochSecond, "sign", MD5Utils.md5(message));

        return R.ok().data(data);
    }

    @GetMapping("/qrcode/detail")
    public R<?> coffeeQrcode(@RequestParam("cid") Long cid,
                                     @RequestParam("time") Long time ,
                                     @RequestParam("sign") String sign) {

        String message = "cid=" + cid + "&key=haredot&time=" + time;

        if (!MD5Utils.md5(message).equals(sign)) {
            return R.fail("签名不正确").build() ;
        }
        // 根据 二维码 扫描到的数据、查询详情
        return orderService.queryOrderDetail(cid) ;

    }

    @PostMapping("/apply")
    public R<?> applyCoffee(@RequestBody @Validated(Insert.class) Order order) {
        User currentUser = TokenContextHolder.getCurrentUser();
        // 获取当前登录的用户
        order.setApplyUserId(currentUser.getId());

        return orderService.applyCoffee(order);
    }

    @GetMapping("/coffeelist")
    public R<?> coffeeList(@RequestParam(value = "state", defaultValue = "2", required = false)
                                       @Valid @Range(min = 0, max = 3, message = "订单状态有误") Integer state) {
        User currentUser = TokenContextHolder.getCurrentUser();
        return orderService.queryCoffeeList(currentUser.getId(), state);
    }

}
